<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-03-01
 * @Time: 10:35
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： Ask.php
 */
namespace app\api\model\ask;

use app\api\controller\User;
use app\api\model\Teacher;
use app\api\model\user\Users;
use app\common\model\UserCreditRecord;
use think\Db;
use think\db\Query;
use think\Log;
use think\Model;

/**
 * Class Ask
 * @package app\api\model\ask
 *
 * @property mixed ask_id
 * @property mixed ask_user
 * @property mixed ask_teacher
 * @property mixed ask_content
 * @property mixed ask_img
 * @property mixed ask_credit
 * @property mixed ask_time
 * @property mixed ask_status
 * @property mixed answer_time
 * @property mixed like_num
 * @property mixed message_num
 */
class Ask extends Model {
    protected $table = 'ask';
    protected $pk = 'ask_id';
    protected $field = [
        'ask_id',
        'ask_user',
        'ask_teacher',
        'ask_content',
        'ask_img',
        'ask_credit',
        'ask_time',
        'ask_status',
        'answer_time',
        'like_num',
        'message_num',
    ];

    const STATUS_WAIT_ANSWER = 0;
    const STATUS_HAVE_ANSWER = 1;
    const STATUS_EXPIRED     = 3;

    protected static $model = null;
    public static function model(): Ask {
        if (empty(self::$model)) {
            self::$model = new self();
        }
        return self::$model;
    }

    public static function teacherManageList($teacherId = 0, $rows = 10, $page = 1, $status = -1) {
        $query = self::model()
            ->join('users u','u.id=ask_user')
            ->where('ask.ask_teacher', $teacherId)
            ->field('ask.*, u.mobile,u.nickname,u.avatar');
        if ($status != -1) $query->where('ask.ask_status', $status);
        else $query->whereIn('ask.ask_status', [self::STATUS_WAIT_ANSWER,self::STATUS_HAVE_ANSWER]);
        $query->order('ask.ask_time desc');
        $result = $query->paginate($rows,false, ['page' => $page]);
        foreach ($result->getCollection() as $item) {
            $item->ask_img = json_decode($item->ask_img,true);
            if (empty($item->nickname)) $item->nickname = mobile_hidden($item->mobile);
        }
        return $result;
    }

    // 偷看花费积分 todo 临时免费偷看 20180420
    public static $viewCredit = 0;

    /**
     * askPost
     * 保存用户提问数据到数据库
     *
     * @author zhengkai
     * @date   2018-03-02
     *
     * @param $uid
     * @param $teacherId
     * @param string $content
     * @param array $img
     * @return \think\response\Json
     */
    public static function askPost($uid, $teacherId, $content='', $img=[])
    {
        // 获取提问所需积分
        $credit = Teacher::getConfigs($teacherId, 'ask_credit');

        // 检测用户积分是否满足提问所需积分
        if (!Users::checkCreditAmount($uid, $credit)) return json(array('code'=>1015, 'msg'=>'积分不足', 'data'=>null));

        Db::startTrans();
        try {

            $field = [
                'ask_user' => $uid,
                'ask_teacher' => $teacherId,
                'ask_content' => $content,
                // 'ask_img' => $img,
                'ask_credit' => $credit
            ];
            if (!empty($img)) $field['ask_img'] = $img;
            $data = self::create($field);

            Db::commit();

            // 更新用户积分，并产生积分变动记录
            Users::consumeCredit($uid,UserCreditRecord::CHANGE_TYPE_ASK, $credit,'付费问答', ['ask_id' => $data->ask_id]);

            return json(array('code'=>200, 'msg'=>'success', 'data'=>null));
        } catch (\Exception $e) {
            Log::error('保存用户提问错误信息：'.$e->getMessage());

            Db::rollback();

            return json(array('code'=>1012, 'msg'=>'fail', 'data'=>null));
        }
    }

    /**
     * askList
     * 获取获取所有用户提问数据（未回答、已回答）
     *
     * @author zhengkai
     * @date 2018-03-05
     *
     * @param int $uid 用户id
     * @param int $page 当前页数
     * @param int $limit 每页加载条数
     * @return false|static[]
     */
    public static function queryAllAsk($uid, $page=1, $limit=10)
    {
        $data = self::all(function ($query) use (&$page, &$limit) {
            // $query->where('ask_status', '<>', 3)
            $query->order('ask_time desc, answer_time desc')
                ->page($page, $limit);
        });

        $list = [];
        foreach ($data as $key=>$val) {
            // 提问用户信息
            $user = Users::getBaseInfo($val['ask_user']);
            $val['user_nickname'] = $user['nickname'];
            $val['user_avatar'] = $user['avatar'];

            $val['ask_teacher_id'] = $val['ask_teacher'];
            $val['ask_teacher'] = Teacher::getBaseTeacher($val['ask_teacher'])['teacher_name'];

            // 图片数据处理
            $val['ask_img'] = json_decode($val['ask_img'], true);
            $val['ask_img'] = count($val['ask_img'])?$val['ask_img']:[];

            // 问题回答时限计算，48小时内
            $val['deadline'] = 48-floor((time()-strtotime($val['ask_time']))/60/60);
            $val['deadline'] = $val['deadline']<=0?0:$val['deadline'];

            $val['like_status'] = AskLiked::userLikeStatus($uid, $val['ask_id']);

            unset($val['ask_time'], $val['answer_time']);

            // 只加载未过期的数据，过期时间48小时
            // if ($val['deadline'] || $val['like_status']) $list[] = $val;
            $list[] = $val;
        }

        return $list;
    }

    /**
     * teacherAskTotal
     * 统计单个老师回答问题总数
     *
     * @author zhengkai
     * @date 2018-03-05
     *
     * @param $tid
     * @return int|string
     */
    public static function teacherAnswerAskTotal($tid)
    {
        $data = self::where('ask_teacher', $tid)->where('ask_status', 1)->count();

        return $data;
    }

    /**
     * teacherLikeAskTotal
     * 计算单个老师已回答问题的被点赞总数
     *
     * @author zhengkai
     * @date 2018-03-05
     *
     * @param $tid
     * @return float|int
     */
    public static function teacherLikeAskTotal($tid)
    {
        $data = self::where('ask_teacher', $tid)->where('ask_status', 1)->sum('like_num');

        return $data;
    }

    /**
     * getSingleField
     * 获取单条问答数据的指定字段值
     *
     * @author zhengkai
     * @date 2018-03-05
     *
     * @param int $askId 问题id
     * @param string $fieldName 字段名称
     * @return mixed
     */
    public static function getSingleField($askId, $fieldName)
    {
        $data = self::get(function($query) use (&$askId) {
            $query->where('ask_id', $askId);
        });

        if ($data) {
            return $data->$fieldName;
        } else {
            return null;
        }
    }

    /**
     * getSingleAsk
     * 获取单条问答数据
     *
     * @author zhengkai
     * @date 2018-03-07
     *
     * @param int $uid 用户id
     * @param int $askId 问答id
     * @return null|static
     */
    public static function getSingleAsk($uid, $askId)
    {
        $data = self::get(function ($query) use (&$askId) {
            $query->where('ask_id', $askId);
        });

        $data->ask_teacher_id = $data->ask_teacher;
        $data->ask_teacher = Teacher::getBaseTeacher($data->ask_teacher)['teacher_name'];
        $data->ask_time = tranTime(strtotime($data->ask_time));

        // 提问用户信息
        $user = Users::getBaseInfo($data->ask_user);
        $data->user_nickname = $user['nickname'];
        $data->user_avatar = $user['avatar'];

        // 图片数据处理
        $data->ask_img = json_decode($data->ask_img, true);
        $data->ask_img = count($data->ask_img)?$data->ask_img:[];

        $data->like_status = AskLiked::userLikeStatus($uid, $data->ask_id);

        $data->view_credit = self::$viewCredit;

        // 问题回答数据处理
        if ($data->ask_status===1) {
            $teacherAnswer = Db::query("select teacher_id,content,img,times from ask_answer where ask_id=:ask_id", ['ask_id'=>$data->ask_id]);
            $teacherAnswer = $teacherAnswer[0];

            $teacherAnswer['times'] = tranTime(strtotime($teacherAnswer['times']));

            // 回答问题老师信息
            $teacher = Teacher::getBaseTeacher($teacherAnswer['teacher_id']);
            $teacherAnswer['teacher_name'] = $teacher['teacher_name'];
            $teacherAnswer['teacher_avatar'] = $teacher['teacher_avatar'];
            $teacherAnswer['teacher_degree'] = $teacher['teacher_degree'];

            // 图片数据处理
            $teacherAnswer['img'] = json_decode($teacherAnswer['img'], true);
            $teacherAnswer['img'] = count($teacherAnswer['img'])?$teacherAnswer['img']:[];

            $answer = $teacherAnswer;
        } else {
            $answer = (object)[];
        }

        // 问题答案查看权限
        $isView = AskView::checkView($uid, $askId);
        if ($data->ask_user===$uid || $isView) {
            $data->is_view = 1;
            $data->ask_answer = $answer;
        } else {
            $data->is_view = 0;
            if ($data->ask_status===1) {
                $data->ask_answer = [
                    'teacher_id' => $teacherAnswer['teacher_id'],
                    'times' => $teacherAnswer['times'],
                    'teacher_name' => $teacherAnswer['teacher_name'],
                    'teacher_avatar' => $teacherAnswer['teacher_avatar'],
                    'teacher_degree' => $teacherAnswer['teacher_degree']
                ];
            } else {
                $data->ask_answer = (object)[];
            }

        }

        unset($data->ask_user, $data->answer_time);

        return $data;
    }

    /**
     * checkCredit
     * 检测用户积分进行提问或偷看问题答案时是否足够
     *
     * @author zhengkai
     * @date 2018-03-07
     *
     * @param int $type 业务类型：1=提问 2=偷看问题答案
     * @param int $uid 用户id
     * @param int $teacherId 老师id，type=2时可不传
     * @return \think\response\Json
     */
    public static function checkCredit($type, $uid, $teacherId=0) {
        $userCredit = Users::getCredit($uid);

        switch ($type) {
            case 1: // 提问
                $useCredit = Teacher::getConfigs($teacherId, 'ask_credit');

                $data = [
                    'user_credit' => $userCredit,
                    'need_credit' => $useCredit
                ];

                if (!Users::checkCreditAmount($uid, $useCredit)) return json(array('code'=>1015, 'msg'=>'积分不足', 'data'=>$data));

                return json(array('code'=>200, 'msg'=>'success', 'data'=>$data));
                break;
            case 2: // 偷看
                $useCredit = self::$viewCredit;

                $data = [
                    'user_credit' => $userCredit,
                    'need_credit' => $useCredit
                ];

                if (!Users::checkCreditAmount($uid, $useCredit)) return json(array('code'=>1015, 'msg'=>'积分不足', 'data'=>$data));

                return json(array('code'=>200, 'msg'=>'success', 'data'=>$data));
                break;
        }
    }

    /**
     * getUserAsk
     * 获取单个用户的问答数据
     *
     * @author zhengkai
     * @date 2018-03-08
     *
     * @param int $uid 用户id
     * @param int $status 问答状态：0=未回答，1=已回答，3=已过期
     * @param int $page 当前页数，默认1
     * @param int $limit 每页加载条数，默认10
     * @return false|static[]
     */
    public static function getUserAsk($uid, $status=0, $page=1, $limit=10)
    {
        $data = self::all(function ($query) use (&$uid, &$status, &$page, &$limit){
            $query->alias('a')
                ->join('ask_answer aa', 'a.ask_id=aa.ask_id', 'left')
                ->field('
                a.ask_id,
                a.ask_teacher,
                a.ask_content,
                a.ask_time,
                a.like_num,
                a.message_num,
                a.ask_status,
                aa.content as answer_content,
                aa.img as answer_img,
                aa.times as answer_time
                ')
                ->where('a.ask_user', $uid);
            if ($status!=99) $query->where('a.ask_status', $status);
            $query->order('a.ask_time desc');
            $query->page($page, $limit);
        });

        $list = [];
        foreach ($data as $key=>$val) {
            $teacher = Teacher::getBaseTeacher($val['ask_teacher']);
            $val['teacher_id'] = $val['ask_teacher'];
            $val['ask_teacher'] = $teacher['teacher_name'];
            $val['teacher_avatar'] = $teacher['teacher_avatar'];

            // 问题回答时限计算，48小时内
            $val['deadline'] = 48-floor((time()-strtotime($val['ask_time']))/60/60);
            $val['deadline'] = $val['deadline']<=0?0:$val['deadline'];

            // 问题回答数据处理
            $val['answer_content'] = empty($val['answer_content'])?'':$val['answer_content'];
            $val['answer_time'] = empty($val['answer_time'])?'':tranTime(strtotime($val['answer_time']));

            // 问题回答图片
            $val['answer_img'] = json_decode($val['answer_img'], true);
            $val['answer_img'] = count($val['answer_img'])?$val['answer_img']:[];

            $list[] = $val;
        }

        return $data;
    }

    /**
     * delAsk
     * 删除过期问答数据
     *
     * @author zhengkai
     * @date 2018-03-08
     *
     * @param int $uid 用户id
     * @param int $askId 问答id
     * @return bool
     */
    public static function delAsk($uid, $askId)
    {
        $ask = Db::query("select ask_id, ask_status from ask where ask_id=:askId and ask_user=:uid", ['askId'=>$askId, 'uid'=>$uid]);
        if (empty($ask)) return false;
        $ask = $ask[0];

        if ($ask['ask_status']!=3) return false;

        Db::startTrans();
        try {
            Db::query("delete from ask_liked where ask_id=:askId", ['askId'=>$askId]); // 删除点赞
            Db::query("delete from ask_message where ask_id=:askId", ['askId'=>$askId]); // 删除留言
            Db::query("delete from ask_answer where ask_id=:askId", ['askId'=>$askId]); // 删除回答
            Db::query("delete from ask where ask_id=:askId and ask_user=:uid", ['askId'=>$askId, 'uid'=>$uid]); // 删除问答

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Log::error('删除问答错误信息：'.$e->getMessage());

            Db::rollback();

            return false;
        }
    }


    /**
     * teacherAsk
     * 获取老师的问答数据
     *
     * @author zhengkai
     * @date 2018-03-09
     *
     * @param int $teacherId 老师id
     * @param int $uid 用户id
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function teacherAsk($teacherId, $uid, $page=1, $limit=10)
    {
        $data = self::all(function ($query) use (&$teacherId, &$page, &$limit) {
            $query->where('ask_status', '<>', 3)
                ->where('ask_teacher', $teacherId)
                ->order('ask_time desc, answer_time desc')
                ->page($page, $limit);
        });

        $list = [];
        foreach ($data as $key=>$val) {
            // 提问用户信息
            $user = Users::getBaseInfo($val['ask_user']);
            $val['user_nickname'] = $user['nickname'];
            $val['user_avatar'] = $user['avatar'];

            $val['ask_teacher'] = Teacher::getBaseTeacher($val['ask_teacher'])['teacher_name'];

            // 图片数据处理
            $val['ask_img'] = json_decode($val['ask_img'], true);
            $val['ask_img'] = count($val['ask_img'])?$val['ask_img']:[];

            // 问题回答时限计算，48小时内
            $val['deadline'] = 48-floor((time()-strtotime($val['ask_time']))/60/60);
            $val['deadline'] = $val['deadline']<=0?0:$val['deadline'];

            $val['like_status'] = AskLiked::userLikeStatus($uid, $val['ask_id']);

            unset($val['ask_time'], $val['answer_time']);

            $list[] = $val;
        }

        return $list;
    }

    /**
     * getHotAsk
     * 获取热门问答数据
     *
     * @author zhengkai
     * @date 2018-04-23
     *
     * @return false|static[]
     * @throws \think\exception\DbException
     */
    public static function getHotAsk()
    {
        $data = self::all(function ($query) {
            $query->alias('ask');
            $query->join('users u', 'ask.ask_user=u.id', 'left');
            $query->join('teacher t', 'ask.ask_teacher=t.id', 'left');
            $query->join('ask_answer aa', 'ask.ask_id=aa.ask_id', 'left');
            $query->field('
            u.id as user_id, u.mobile as user_mobile, u.nickname as user_nickname, u.avatar as user_avatar,
            ask.ask_id, ask.ask_content, ask.ask_status, ask.like_num, ask.message_num, ask.ask_time,
            t.realname as teacher_realname, aa.content as answer_content
            ');
            $query->order('ask.ask_time desc,like_num desc, message_num desc');
            $query->limit(0, 4);
        });

        foreach ($data as &$val) {
            $val['user_nickname'] = ($val['user_nickname']?:mobile_hidden(substr($val['user_mobile'], 0, 11)))?:$val['user_id'];
            $val['user_avatar'] = $val['user_avatar']?:Users::defaultAvatar();

            // 问题回答时限计算，48小时内
            $val['ask_deadline'] = 48-floor((time()-strtotime($val['ask_time']))/60/60);
            $val['ask_deadline'] = $val['ask_deadline']<=0?0:$val['ask_deadline'];

            unset($val['user_id'], $val['user_mobile'], $val['ask_time'], $val['answer_content']);
        }

        return $data;
    }
}